#!/usr/bin/env python
import pygame
from os.path import join
from OpenGL.GL import *

class glString(object):
    def __init__(self, font, x, y, string):
        self.font = font
        self.x = x
        self.y = y
        self.string = [font.chars[ord(c)] for c in string]

    def glPrint(self):
        x, y = self.x, self.y
        glPushMatrix()
        for c in self.string:
            glRasterPos(x, y, 0.0)
            #glPixelZoom(1, 1)
            glDrawPixels(c.width, c.height, GL_RGBA, GL_UNSIGNED_BYTE, c.image)
            x += c.width*1.5
        glPopMatrix()

class glFont(pygame.font.Font):
    def __init__(self, name, size=12,
                 foregroundColor=(255, 255, 255),
                 backgroundColor=None,
                 antialiased=True):
        self.foregroundColor = foregroundColor
        self.backgroundColor = backgroundColor
        self.antialiased = antialiased
        pygame.font.Font.__init__(self, name, size)
        self.chars = [self._getChar(chr(c)) for c in xrange(0, 256)]
        f = open(join('data', 'out.txt'), mode='wb')
        for s in self.chars:
            f.write(str(s))
        f.close()
    def _getChar(self, c):
        class Char(object):
            pass
        char = Char()
        try:
            # Pygame won't allow you to explicitly pass in None for background
            # color, even though that's the default. Can you say "WTF?"
            if self.backgroundColor is None:
                char_prepped = self.render(c, self.antialiased, self.foregroundColor)
            else:
                char_prepped = self.render(c, self.antialiased,
                                           self.foregroundColor,
                                           self.backgroundColor)
            char.image = pygame.image.tostring(char_prepped, 'RGBA', 1)
            char.width, char.height = char_prepped.get_size()
            del char_prepped
        except pygame.error as e:
            #print(e, '--- Char:', c)
            char.image = None
            char.width = 0
            char.height = 0
        return char